package leetCode.thread.leetCode1115;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁配合信号量
 */
public class FooBar4 implements FooBar {

    private int n;

    Lock lock = new ReentrantLock(true);
    private final Condition foo = lock.newCondition();
    volatile boolean flag = true;

    @Override
    public void foo(Runnable printFoo) throws InterruptedException {
        for(int i=0;i<n;i++){
            lock.lock();
            try {
                while (!flag){
                    foo.await();
                }
                printFoo.run();
                flag = false;
                foo.signal();
            }finally {
                lock.unlock();
            }
        }
    }

    @Override
    public void bar(Runnable printBar) throws InterruptedException {
        for(int i=0;i<n;i++) {
            lock.lock();
            try{
                while(flag){
                    foo.await();
                }
                printBar.run();
                flag = true;
                foo.signal();
            }finally {
                lock.unlock();
            }
        }
    }

}
